const Sports = require("../models/sports");
const SportsUseNum = require("../models/sportsusenum");
const collectServices = require("../services/collectService");
const sequelize = require("../config/sequelize");
const { changekeyWord } = require("../utils/changeKeyword");
const { Op } = require("sequelize");

//按关键字搜索运动
exports.search = async function (value) {
  const searchKey = changekeyWord(value);
  return Sports.findAll({
    where: {
      name: {
        [Op.regexp]: searchKey,
      },
    },
    attributes: ["id", "name", "img", "heat"],
  });
};

exports.getOftenAndCollect = async function (userId) {
  const oftenUseArr = await SportsUseNum.findAll({
    where: { userId },
    attributes: ["id", "num"],
    include: {
      model: Sports,
      attributes: ["id", "img", "name", "heat"],
      as: "sports",
    },
    order: [["num", "DESC"]],
  });
  for (item of oftenUseArr) {
    const sportsId = item.dataValues.sports.id;
    item.dataValues.sports.dataValues.isCollect =
      await collectServices.isCollect(userId, sportsId, "sports");
  }
  const collectArr = await collectServices.collectSports(userId);
  collectArr.forEach((item) => {
    item.dataValues.sports.dataValues.isCollect = true;
  });

  return {
    oftenUseArr,
    collectArr,
  };
};

